<template>
  <el-form ref="ruleForm" label-width="100px" class="demo-ruleForm">
    <el-form-item label="用户名" prop="username">
      <el-input v-model="form.username"
                autocomplete="off"
                placeholder="请输入用户名" autosize>
      </el-input>
    </el-form-item>
    <el-form-item label="密码">
      <el-input type="password" autocomplete="off" v-model="form.pwd" placeholder="请输入密码">
      </el-input>
    </el-form-item>
    <el-form-item>
      <el-button class="login_button" @click="clickRegButton">注册</el-button>
      <el-button type="primary" class="login_button" @click="clickLoginButton">登陆</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import axios from "axios";
import {router} from "@/routers";
import {UserMe} from "@/user";

export default {
  name: "LoginForm",
  data() {
    return {
      form: {
        username: '',
        pwd: '',
        info: null,
      },
    }
  },
  mounted() {
  },
  methods: {
    mobileErrAlert(msg) {
      this.$notify.error({
        title: '错误',
        message: msg,
      });
    },
    clickRegButton() {
      axios.post('http://localhost:1110/reg', {
        username: this.form.username,
        pwd: this.form.pwd
      }).then(response => (this.info = response)).then(
          () => {
            let meta = this.info.data.meta
            if (meta.code !== 0) {
              this.mobileErrAlert(meta.msg)
            } else {
              let user = this.info.data.user
              UserMe.id = user.id
              UserMe.head_url = user.head_url
              UserMe.username = user.username
              router.push("/index")
            }
          }
      )
    },
    clickLoginButton() {
      axios.post('http://localhost:1110/login', {
        username: this.form.username,
        pwd: this.form.pwd
      }).then(response => (this.info = response)).then(
          () => {
            let meta = this.info.data.meta
            if (meta.code !== 0) {
              this.mobileErrAlert(meta.msg)
            } else {
              let user = this.info.data.user
              UserMe.id = user.id
              UserMe.head_url = user.head_url
              UserMe.username = user.username
              router.push("/index")
            }
          }
      )
    }
  }
}

</script>

<style scoped>
.login_button {
  width: 8rem;
}
</style>